package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.AdvertisementDetailActivity;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.MultipleCouponDetailActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.constant.StatementConstant;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.Statement;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.service.StatementService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.math.BigDecimal;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 保证金收支清单适配器
 */
public class DepositStatementAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "BalanceStatementAdapter";
    private List<Statement> statementList;

    private boolean bol_noData;//标记是否有数据
    private boolean bol_requestError;//标记是否请求出错
    private Context mContext;


    public DepositStatementAdapter(Context context, List<Statement> couponList) {
        mContext = context;
        this.statementList = couponList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            return new NoDataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.no__data__layout, parent, false));
        } else if (viewType == Constant.ITEM_TYPE_REQUEST_ERROR) {
            return new RequestErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.request_error_layout, parent, false));
        }
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.statement_item, parent, false);

        return new ItemViewHolder(view);
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        int viewType = getItemViewType(position);
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            NoDataViewHolder noDataViewHolder = (NoDataViewHolder) holder;
            noDataViewHolder.tv_tips.setText("没有记录");
        } else if (viewType == Constant.ITEM_TYPE_NORMAL) {
            ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
            setItemViews(itemViewHolder, position);
        }
    }


    private void setItemViews(ItemViewHolder itemViewHolder, int position) {
        Statement statement = statementList.get(position);
        BigDecimal amount = statement.getAmount();
        if (amount.compareTo(BigDecimal.ZERO) > 0) {
            itemViewHolder.tvMoneyAmount.setTextColor(mContext.getResources().getColor(R.color.rp_money_red_light));
            itemViewHolder.tvMoneyAmount.setText("+" + Utils.moneyFormat(amount));
        } else {
            itemViewHolder.tvMoneyAmount.setTextColor(mContext.getResources().getColor(R.color.text_black));
            itemViewHolder.tvMoneyAmount.setText(Utils.moneyFormat(amount));
        }
        itemViewHolder.tvDate.setText(DateUtils.getTimestampString(statement.getCreated()));
        itemViewHolder.itemView.setOnLongClickListener(v -> {
            ConfirmDialog dialog = new ConfirmDialog(mContext, "提醒", "确定删除本条记录吗？", true);
            dialog.setConfirmListener(() -> deleteStatement(statement.getId(), position));
            dialog.show();
            return true;
        });

        switch (statement.getType()) {
            case StatementConstant.STATEMENT_TYPE_ADVERTISEMENT_DEPOSIT:
                handleAdvertisementDepositStatement(itemViewHolder, statement);
                break;
            case StatementConstant.STATEMENT_TYPE_REWARD_DEPOSIT:
                handleRewardDepositStatement(itemViewHolder, statement);
                break;
        }
    }

    private void handleAdvertisementDepositStatement(ItemViewHolder itemViewHolder, Statement statement) {

        itemViewHolder.tv_title.setText(statement.getTitle());
        showIcon(itemViewHolder, statement);
        itemViewHolder.itemView.setOnClickListener(v -> AdvertisementDetailActivity.startActivity(mContext, statement.getTargetId()));
        Integer subtype = statement.getSubtype();
        if (subtype == null) {
            Log.e(TAG, "handleRewardDepositStatement: 类型为空，，，" + JSONObject.toJSONString(statement));
            return;
        }
        switch (subtype) {
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_DEPOSIT_PUT:
                itemViewHolder.tv_type.setText("[广告位投放]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_DEPOSIT_INCREASE:
                itemViewHolder.tv_type.setText("[广告位保证金追加]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_DEPOSIT_REVOKE:
                itemViewHolder.tv_type.setText("[广告位保证金撤回]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_ADVERTISEMENT_OFFER_SUCCESS_DEPOSIT_REDUCE:
                itemViewHolder.tv_type.setText("[广告位竞价成功，保证金自动返还]");
                break;
        }

    }

    private void handleRewardDepositStatement(ItemViewHolder itemViewHolder, Statement statement) {
        itemViewHolder.tv_title.setText(statement.getTitle());
        showIcon(itemViewHolder, statement);
        itemViewHolder.itemView.setOnClickListener(v -> TopicDetailsActivity.startActivity(mContext, statement.getTargetId()));
        Integer subtype = statement.getSubtype();
        if (subtype == null) {
            Log.e(TAG, "handleRewardDepositStatement: 类型为空，，，" + JSONObject.toJSONString(statement));
            return;
        }
        switch (subtype) {
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_PUBLISH:
                itemViewHolder.tv_type.setText("[发布悬赏]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_AMOUNT_INCREASE:
                itemViewHolder.tv_type.setText("[悬赏金增加]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_AMOUNT_REDUCE:
                itemViewHolder.tv_type.setText("[悬赏金减少]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_CANCEL:
                itemViewHolder.tv_type.setText("[悬赏取消]");
                break;
            case StatementConstant.STATEMENT_SUBTYPE_REWARD_COMPLETE:
                itemViewHolder.tv_type.setText("[悬赏完成]");
                break;
            default:
                Log.e(TAG, "handleRewardDepositStatement: 有类型没有处理，，，，，" + JSONObject.toJSONString(statement));
        }
    }

    private void showIcon(ItemViewHolder itemViewHolder, Statement statement) {
        String iconUrl = Utils.getIconUrl(statement);
        if (GlideLoadUtils.isActivityAlive((Activity) mContext)) {
            Glide.with(mContext).load(iconUrl).transform(new CircleCrop()).into(itemViewHolder.ivAvatar);
        }
    }

    private void deleteStatement(String id, int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) mContext).showToast_v1(mContext.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(StatementService.class)
                .deleteStatement(id)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "删除出错：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "删除出错：" + result.getMsg());
                            return;
                        }
                        statementList.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, statementList.size() - position);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });

    }

    @Override
    public int getItemCount() {
        if (bol_noData || bol_requestError) {
            return 1;
        }
        return statementList.size();
    }


    @Override
    public int getItemViewType(int position) {
        if (bol_noData) {
            return Constant.ITEM_TYPE_NO_DATA;
        } else if (bol_requestError) {
            return Constant.ITEM_TYPE_REQUEST_ERROR;
        }
        return Constant.ITEM_TYPE_NORMAL;
    }


    /**
     * 显示普通视图
     * 有数据的时候调用
     */
    public void showNormalView() {
        bol_noData = false;
        bol_requestError = false;
        notifyDataSetChanged();
    }

    /**
     * 显示无数据视图
     */
    public void showNoDataView() {
        bol_noData = true;
        notifyDataSetChanged();
    }

    /**
     * 显示请求数据错误视图
     */
    public void showErrorView() {
        bol_requestError = true;
        notifyDataSetChanged();
    }

    private static class ItemViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar;
        TextView tv_title;
        TextView tvDate;
        TextView tvMoneyAmount;
        TextView tv_type;

        ItemViewHolder(View v) {
            super(v);
            initView(v);
        }

        private void initView(View v) {
            ivAvatar = v.findViewById(R.id.iv_item_avatar_icon);
            tv_title = v.findViewById(R.id.tv_title);
            tvDate = v.findViewById(R.id.tv_time);
            tvMoneyAmount = v.findViewById(R.id.tv_item_money_amount);
            tv_type = v.findViewById(R.id.tv_type);
        }
    }


}
